package com.cj.stock.service.impl;

import com.cj.stock.service.SpikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author cheng jun
 * @Description: 单体系统（synchronized锁满足不了集群或者分布式环境下的高并发需求，出现超卖现象）
 * @Date 2021/8/8 16:56
 */
@Service("level1SpikeServiceImpl")
@Slf4j
public class Level1SpikeServiceImpl implements SpikeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Async("taskExecutor")
    public boolean spikeStock() {
        String inStock = "inStock";
        try {
            synchronized (this) {
                // 从redis拿库存
                int stock = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(inStock)));
                if (stock > 0) {
                    // 重新设置库存大小
                    int realStock = stock - 1;
                    redisTemplate.opsForValue().set(inStock, realStock);
                    log.info("减库存成功,剩余库存数:" + realStock);
                } else {
                    log.info("库存不够");
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        }

        return true;
    }
}
